<template>
  <div class="edit-report">
    <div class="page-header">
      <h1>编辑日报</h1>
      <p>修改日报内容和进展</p>
    </div>

    <div class="report-form" v-if="!loading">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        size="large"
      >
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="工作内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请描述今日的主要工作内容"
          />
        </el-form-item>

        <el-form-item label="工作时长" prop="workHours">
          <el-input-number
            v-model="form.workHours"
            :min="0"
            :max="24"
            :precision="1"
            placeholder="工作时长（小时）"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="项目" prop="projectId">
          <el-select
            v-model="form.projectId"
            placeholder="选择项目"
            style="width: 100%"
          >
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="完成进度" prop="progress">
          <el-slider
            v-model="form.progress"
            :min="0"
            :max="100"
            :step="5"
            show-input
            :format-tooltip="(val: number) => `${val}%`"
          />
        </el-form-item>

        <el-form-item label="心情状态" prop="mood">
          <el-radio-group v-model="form.mood">
            <el-radio value="excited">😄 兴奋</el-radio>
            <el-radio value="happy">😊 开心</el-radio>
            <el-radio value="normal">😐 一般</el-radio>
            <el-radio value="tired">😴 疲惫</el-radio>
            <el-radio value="sad">😢 难过</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            placeholder="选择或输入标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            更新日报
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="loading-container" v-else>
      <el-skeleton :rows="8" animated />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useProjectStore } from '@/stores/project'
const router = useRouter()
const route = useRoute()
const projectStore = useProjectStore()

const formRef = ref<FormInstance>()
const loading = ref(true)
const submitting = ref(false)
const projects = ref<any[]>([])
const reportId = ref(Number(route.params.id))

const commonTags = ['开发', '测试', '设计', '会议', '文档', '优化', 'Bug修复', '需求分析']

const form = reactive({
  date: new Date(),
  content: '',
  workHours: 8,
  projectId: null as number | null,
  progress: 0,
  mood: 'normal',
  tags: [] as string[]
})

const rules: FormRules = {
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入工作内容', trigger: 'blur' },
    { min: 10, message: '工作内容至少10个字符', trigger: 'blur' }
  ],
  workHours: [
    { required: true, message: '请输入工作时长', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ],
  progress: [
    { required: true, message: '请设置完成进度', trigger: 'blur' }
  ],
  mood: [
    { required: true, message: '请选择心情状态', trigger: 'change' }
  ]
}

const loadReportData = async () => {
  try {
    loading.value = true
    
    // 模拟获取日报数据
    const mockReport = {
      id: reportId.value,
      date: new Date('2024-01-17'),
      workContent: '完成了用户登录功能的开发，包括前端页面设计和后端API接口实现。修复了登录页面样式问题，优化了用户体验。',
      workHours: 8,
      projectId: 1,
      progress: 85,
      mood: 'happy',
      tags: ['开发', '前端', '后端', 'Bug修复']
    }
    
    // 填充表单数据
    form.date = mockReport.date
    form.content = mockReport.workContent
    form.workHours = mockReport.workHours
    form.projectId = mockReport.projectId
    form.progress = mockReport.progress
    form.mood = mockReport.mood
    form.tags = mockReport.tags
    
  } catch (error) {
    console.error('加载日报数据失败:', error)
    ElMessage.error('加载日报数据失败')
    router.push('/reports')
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 这里应该调用API更新日报
    // await reportStore.updateReport(reportId.value, {
    //   id: reportId.value,
    //   userId: 1,
    //   reportDate: form.date.toISOString().split('T')[0],
    //   workContent: form.content,
    //   workHours: form.workHours,
    //   projectId: form.projectId || 1,
    //   progress: form.progress,
    //   mood: form.mood,
    //   tags: form.tags
    // })
    
    ElMessage.success('日报更新成功')
    router.push({ name: 'Reports' })
  } catch (error) {
    console.error('更新日报失败:', error)
    ElMessage.error('更新日报失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

const goBack = () => {
  router.back()
}

onMounted(async () => {
  try {
    // 加载项目列表
    await projectStore.fetchProjects()
    let projectList = projectStore.projects as any[]
    
    // 临时修复：替换乱码的项目名称为正确的中文名称
    if (projectList && projectList.length > 0) {
      projectList = projectList.map((project, index) => {
        const correctNames = [
          '用户管理系统',
          '电商平台开发',
          '移动应用项目',
          '数据分析平台',
          '企业官网重构'
        ]
        return {
          ...project,
          name: correctNames[index] || `项目${project.id}`
        }
      })
    }
    
    projects.value = projectList
    
    // 加载日报数据
    await loadReportData()
  } catch (error) {
    console.error('初始化失败:', error)
    // 如果获取失败，提供默认项目列表
    projects.value = [
      { id: 1, name: '用户管理系统' },
      { id: 2, name: '电商平台开发' },
      { id: 3, name: '移动应用项目' }
    ]
    await loadReportData()
  }
})
</script>

<style scoped>
.edit-report {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-header p {
  margin: 0;
  color: #6b7280;
}

.report-form {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-container {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
}
</style>